package top.yohann.study.common.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author Yeung Wah
 * @since 2021/11/21
 */
public abstract class BaseService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String PREFIX = "common:send_code:";

    protected String getCode(String account) {
        return redisTemplate.opsForValue().get(PREFIX + account);
    }

    protected String generateCode() {
        int randomCode = ThreadLocalRandom.current().nextInt(100000, 999999);
        return String.valueOf(randomCode);
    }

    protected void setCode(String account, String code) {
        redisTemplate.opsForValue().set(PREFIX + account, code, 3, TimeUnit.MINUTES);
    }

    public boolean checkCode(String account, String code) {
        String cacheCode = this.getCode(account);
        if (StringUtils.isEmpty(cacheCode)) {
            return Boolean.FALSE;
        }

        return code.equals(cacheCode);
    }
}